<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <label class="el-form-item-label">名称</label>
        <el-input v-model="query.name" clearable placeholder="名称" style="width: 185px" class="filter-item"
          @keyup.enter.native="crud.toQuery" />
        <label class="el-form-item-label">实验室</label>
        <el-select v-model="query.labId" clearable style="width: 185px" placeholder="实验室" class="filter-item"
          @keyup.enter.native="crud.toQuery">
          <el-option v-for="item in labs" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
        <label class="el-form-item-label">试剂柜</label>
        <el-select v-model="query.cabinetId" clearable style="width: 185px" placeholder="试剂柜" class="filter-item"
          @keyup.enter.native="crud.toQuery">
          <el-option v-for="item in cabinets" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
        <label class="el-form-item-label">危险等级</label>
        <el-select v-model="query.dangerClasses" clearable style="width: 185px" placeholder="危险等级" class="filter-item"
          @keyup.enter.native="crud.toQuery">
          <el-option v-for="item in dangerClassesOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <label class="el-form-item-label">入库时间</label>
        <date-range-picker v-model="query.createdAt" class="date-item" />
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0"
        :title="crud.status.title" width="550px">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="95px">
          <el-form-item label="名称" prop="name">
            <el-select v-model="form.name" style="width: 370px" clearable filterable allow-create reserve-keyword
              :remote-method="getName" placeholder="请添加名称" @visible-change="nameVisible" ref="nameSel">
              <el-option v-for="item in names" :key="item.id" :label="item.name" :value="item.name" />
            </el-select>
          </el-form-item>
          <el-form-item label="级别" prop="grade">
            <el-select v-model="form.grade" style="width: 370px" placeholder="请选择级别" filterable clearable allow-create
              default-first-option @blur="onSelectBlur('grade', 'gradeSel')" ref="gradeSel">
              <el-option v-for="item in gradeOptions" :key="item.label" :label="item.value" :value="item.value" />
            </el-select>
          </el-form-item>
          <div style="display: flex">
            <el-form-item label="规格" prop="capacity">
              <el-input min="0" type="number" v-model="form.capacity" style="width: 170px" />
            </el-form-item>
            <el-form-item class="unit" prop="unit">
              <el-select v-model="form.unit" style="width: 170px" placeholder="请选择单位">
                <el-option v-for="item in unitOptions" :key="item.label" :label="item.value" :value="item.label" />
              </el-select>
            </el-form-item>
          </div>
          <el-form-item label="数量" prop="amount">
            <el-input min="0" type="number" v-model="form.amount" style="width: 350px" placeholder="请填入数量" />瓶
          </el-form-item>
          <el-form-item label="实验室" prop="labId">
            <el-select v-model="form.labId" style="width: 370px" clearable filterable :remote-method="getLabs"
              placeholder="请选择实验室" @change="onChanged">
              <el-option v-for="item in labs" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="form.labId" label="试剂柜" prop="cabinetId">
            <el-select v-model="form.cabinetId" style="width: 370px" clearable filterable :remote-method="getCabinets"
              placeholder="请选择试剂柜">
              <el-option v-for="item in cabinets" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="试剂柜" prop="cabinetId">
            <el-input v-model="form.cabinetId" style="width: 370px;" />
          </el-form-item> -->
          <!-- <el-form-item label="计量方式" prop="measureId">
            未设置字典，请手动设置 Radio
          </el-form-item> -->
          <el-form-item label="危险等级" prop="dangerClasses">
            <el-select v-model="form.dangerClasses" style="width: 370px" placeholder="请选择危险等级">
              <el-option v-for="item in dangerClassesOptions" :key="item.value" :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="是否申领" prop="isApply">
            <el-radio-group v-model="form.isApply" @input="changeIsApply">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item> -->
          <el-form-item label="是否审批" prop="isAudit">
            <el-radio-group v-model="form.isAudit">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="有效期" prop="expirationDate">
            <el-date-picker style="width: 370px" v-model="form.expirationDate" type="date" placeholder="选择有效期"
              :picker-options="pickerOptions">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="form.note" :rows="3" type="textarea" style="width: 370px" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;"
        @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="名称" align="center" />
        <el-table-column label="条码" prop="barCode" align="center">
          <template slot-scope="scope">
            <div class="barCode">
              <el-image :src="
                baseUrl +
                '/api/barCode/showBarCode?id=' +
                scope.row.id +
                '&type=' +
                scope.row.type
              " style="height: 40px; vertical-align: middle" :preview-src-list="srcList"
                @click="enlargeBarcode(scope.row)" />
              <span>{{ scope.row.id }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="二维码" prop="QRCode" align="center">
          <template slot-scope="scope">
            <el-image :src="
                baseUrl +
                '/api/barCode/showQRCode?id=' +
                scope.row.id +
                '&type=' +
                scope.row.type
              " style="height: 40px; vertical-align: middle" :preview-src-list="srcList"
              @click="enlargeQRCode(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column label="级别" prop="grade" align="center">
          <template slot-scope="scope">
            <span :style="classObj(scope.row.grade)">
              {{ scope.row.grade }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="规格" prop="capacity" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.capacity }}</span>
            <span>{{
              scope.row.unit == 1 ? "L" : scope.row.unit == 2 ? "mL" : "g"
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="剩余量" prop="residue" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.residue }}</span>
            <span>{{
              scope.row.unit == 1 ? 'L' : scope.row.unit == 2 ? "mL" : "g"
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="数量" prop="amount" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.amount }} 瓶</span>
          </template>
        </el-table-column>
        <el-table-column prop="labName" label="实验室" align="center" />
        <el-table-column prop="cabinetName" label="试剂柜" align="center" />
        <!-- <el-table-column prop="measureId" label="计量方式" /> -->
        <el-table-column prop="dangerClasses" width="155px" label="危险等级" align="center">
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.dangerClasses == 1">一般试剂(I)</el-tag>
            <el-tag v-if="scope.row.dangerClasses == 2">有机试剂(II)</el-tag>
            <el-tag type="danger" v-if="scope.row.dangerClasses == 3">剧毒试剂/易致毒试剂(III)</el-tag>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="isAudit" label="是否审批" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.isAudit == 0 ? "否" : "是" }}</span>
          </template>
        </el-table-column> -->
        <el-table-column prop="createdAt" label="入库时间" align="center" width="155">
          <template slot-scope="scope">
            <div>
              <div>{{scope.row.createdAt}}</div>
              <div v-if="scope.row.expirationDate">有效期:</div>
              <div v-if="scope.row.expirationDate">{{scope.row.expirationDate}}</div>
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="expirationDate" label="有效期" align="center" width="135" /> -->
        <!-- <el-table-column prop="note" label="备注" align="center" /> -->
        <el-table-column label="条形码" align="center">
          <template slot-scope="scope">
            <button class="el-button el-button--primary el-button--mini" @click="barView(scope.row)">
              <i class="el-icon-printer" size="100" />
            </button>
          </template>
        </el-table-column>
        <el-table-column label="二维码" align="center">
          <template slot-scope="scope">
            <button class="el-button el-button--primary el-button--mini" @click="qrView(scope.row)">
              <i class="el-icon-printer" size="100" />
            </button>
          </template>
        </el-table-column>
        <el-table-column v-if="
            checkPer([
              'admin',
              'hazardousChemicals:edit',
              'hazardousChemicals:del',
            ])
          " label="操作" width="170px" align="center">
          <template slot-scope="scope">
            <el-button type="primary" class="isForbiddenBtn" @click="showAddNumDialog(scope.row)">入库</el-button>
            <el-button type="success" class="isForbiddenBtn" @click="crud.toQuote(scope.row)">引用</el-button>
            <udOperation :data="scope.row" :permission="permission" />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination ref="pag" />
    </div>
    <el-dialog :close-on-click-modal="false" :visible.sync="view" title="打印预览" width="350px">
      <el-image :src="
          baseUrl +
          '/api/barCode/showBarCode?id=' +
          codeId +
          '&type=' +
          codeType
        " />
      <el-button type="primary" @click="fileDownload()" style="margin-left: 40%">
        打印
      </el-button>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" :visible.sync="views" title="打印预览" width="350px">
      <el-image :src="
          baseUrl + '/api/barCode/showQRCode?id=' + codeId + '&type=' + codeType
        " />
      <el-button type="primary" @click="fileDownloadQR()" style="margin-left: 40%">
        打印
      </el-button>
    </el-dialog>
    <AddNumDialog v-if="isShowAddNumDialog" @refresh="crud.pageChangeHandler(0)" @close="isShowAddNumDialog = false"
      :isShowAddNumDialog="isShowAddNumDialog" :info="currentAddNumDialogInfo" />
  </div>
</template>

<script>
  import AddNumDialog from "./components/addNumDialog.vue";
  import crudHazardousChemicals, {
    getLabCabinetListAPI,
  } from "@/api/hazardousChemicals";
  import CRUD, {
    presenter,
    header,
    form,
    crud
  } from "@crud/crud";
  import rrOperation from "@crud/RR.operation";
  import crudOperation from "@crud/CRUD.operation";
  import udOperation from "@crud/UD.operationDelete";
  import pagination from "@crud/Pagination";
  import {
    get
  } from "@/api/lab";
  import {
    getCabinet,
  } from "@/api/cabinet";
  import {
    showBarCode,
    print
  } from "@/api/barCode";
  import DateRangePicker from "@/components/DateRangePicker";
  import {
    printCode
  } from "@/api/barCode";
  import {
    searchName
  } from "@/api/hazardousChemicals";

  const defaultForm = {
    id: null,
    name: null,
    type: 3,
    amount: null,
    capacity: null,
    labId: null,
    note: null,
    createdAt: null,
    isDeleted: null,
    countType: 1,
    updatedAt: null,
    barCode: null,
    cabinetId: null,
    measureId: 1,
    dangerClasses: null,
    grade: null,
    isAudit: 0,
    isApply: 1,
    unit: null,
  };
  export default {
    name: "HazardousChemicals",
    components: {
      pagination,
      crudOperation,
      rrOperation,
      udOperation,
      DateRangePicker,
      AddNumDialog
    },
    mixins: [presenter(), header(), form(defaultForm), crud()],
    cruds() {
      return CRUD({
        title: "化学试剂",
        url: "api/hazardousChemicals",
        idField: "id",
        sort: "id,desc",
        crudMethod: {
          ...crudHazardousChemicals
        },
        query: {
          type: 3,
        },
        optShow: {
          add: true,
          edit: true,
          del: true,
          download: true,
          reset: true,
          printHazardousChemicals: true,
          printQRHazardousChemicals: true,
          chemicalBatchImport: true,
          chemicalUpload: true
        },
      });
    },
    data() {
      let limtAmount = (rule, value, callback) => {
        if (!value) {
          return callback(new Error("数量不能为空"));
        }
        callback();
      };
      let limtName = (rule, value, callback) => {
        if (!value) {
          return callback(new Error("名称不能为空"));
        }
        //else if (this.names.some(item=>item.name==this.form.name)) {
        //  return callback(new Error("该名称物质已入库，请勿重复入库"));
        //}
        callback();
      };
      return {
        currentAddNumDialogInfo: {},
        isShowAddNumDialog: false,
        pickerOptions: {
          disabledDate(time) {
            return time.getTime() < Date.now() - 8.64e7;
          }
        },
        permission: {
          add: ["admin", "hazardousChemicals:add"],
          edit: ["admin", "hazardousChemicals:edit"],
          del: ["admin", "hazardousChemicals:del"],
        },
        rules: {
          name: [{
            required: true,
            trigger: "change",
            validator: limtName
          }, ],
          grade: [{
            required: true,
            message: "级别不能为空",
            trigger: "change"
          }],
          unit: [{
            required: true,
            message: "单位不能为空",
            trigger: "change"
          }],
          amount: [{
            required: true,
            trigger: "blur",
            validator: limtAmount
          }],
          capacity: [{
            required: true,
            message: "规格不能为空",
            trigger: "blur"
          }, ],
          labId: [{
            required: true,
            message: "实验室不能为空",
            trigger: "change"
          }, ],
          cabinetId: [{
            required: true,
            message: "试剂柜不能为空",
            trigger: "change"
          }, ],
          // isApply: [
          //   { required: true, message: "请选择是否需要申领", trigger: "blur" },
          // ],
          isAudit: [{
            required: true,
            message: "请选择是否需要申领",
            trigger: "blur"
          }, ],
          dangerClasses: [{
            required: true,
            message: "危险等级不能为空",
            trigger: "change"
          }, ],
        },
        queryTypeOptions: [{
            key: "name",
            display_name: "名称"
          },
          // { key: 'type', display_name: '危化品类型' },
          {
            key: "labName",
            display_name: "实验室"
          },
          {
            key: "countType",
            display_name: "计数类型"
          },
          {
            key: "cabinetName",
            display_name: "试剂柜"
          },
          // { key: 'measureId', display_name: '计量方式' },
          {
            key: "dangerClasses",
            display_name: "危险等级"
          },
        ],
        labs: [],
        cabinets: [],
        baseUrl: process.env.VUE_APP_BASE_API,
        srcList: [], //预览图片列表
        names: [],
        gradeOptions: [{
            label: 1,
            value: "优级纯",
          },
          {
            label: 2,
            value: "色谱纯",
          },
          {
            label: 3,
            value: "分析纯",
          },
          {
            label: 4,
            value: "化学纯",
          },
          {
            label: 5,
            value: "基准试剂",
          },
          {
            label: 6,
            value: "其他",
          },
        ],
        unitOptions: [{
            value: "L",
            label: 1,
          },
          {
            value: "mL",
            label: 2,
          },
          {
            value: "g",
            label: 3,
          },
        ],
        dangerClassesOptions: [{
            value: 1,
            label: "一般试剂(I)",
          },
          {
            value: 2,
            label: "有机试剂(II)",
          },
          {
            value: 3,
            label: "剧毒试剂/易致毒试剂(III)",
          },
        ],
        openDoorId: "",
        view: false,
        views: false,
        codeId: "",
        codeType: "",
      };
    },
    created() {
      this.getLabCabinetList();
      this.getCabinets();
      this.getName();
      // this.showBarCode()
    },
    computed: {
      classObj(grade) {
        return (grade) => {
          if (grade === "分析纯") {
            return {
              color: "#e94925"
            };
          } else if (grade === "化学纯") {
            return {
              color: "#1890ff"
            };
          } else if (grade === "基准试剂") {
            return {
              color: "lightgreen"
            };
          } else if (grade === "优级纯") {
            return {
              color: "#1da55a"
            };
          } else if (grade === "色谱纯") {
            return {
              color: "#1da55a"
            };
          } else if (grade === "其他") {
            return {
              color: "black"
            };
          }
        };
      },
    },
    methods: {
      showAddNumDialog(row) {
        this.currentAddNumDialogInfo = row
        this.isShowAddNumDialog = true
      },
      getName() {
        searchName(3)
          .then((response) => {
            this.names = response
          })
          .catch((_) => {
            // console.log(response);
          });
        //可通过ref属性获取当前select选择器中的输入内容

      },
      // nameblur(){
      //   this.form.name = this.$refs.nameSel.selectedLabel
      // },
      nameVisible(e) {
        if (e) {
          this.$refs.nameSel.$data.selectedLabel = this.form.name
        }
      },
      changeIsApply(val) {
        if (val == 0) {
          this.form.isAudit = 0;
        }
      },
      async getLabCabinetList() {
        const res = await getLabCabinetListAPI();
        this.labs = res;
      },
      onSelectBlur(form, sel) {
        this.form[form] = this.$refs[sel].selectedLabel;
      },
      getLabs() {
        get()
          .then((response) => {
            this.labs = response;
          })
          .catch((_) => {});
      },
      getCabinets() {
        getCabinet()
          .then((response) => {
            this.cabinets = response.content;
          })
          .catch((_) => {});
      },
      onChanged(value) {
        getCabinet()
          .then((response) => {
            this.cabinets = response.content;
            this.cabinets = this.cabinets.filter((item) => {
              return item.labId == value;
            });
            if (this.cabinets.length != 0) {
              this.form.cabinetId = this.cabinets[0].id;
            } else {
              this.form.cabinetId = null;
            }
          })
          .catch((_) => {
            console.log(response);
          });
      },
      barView(row) {
        this.view = true;
        this.codeId = row.id;
        this.codeType = row.type;
      },
      qrView(row) {
        this.views = true;
        this.codeId = row.id;
        this.codeType = row.type;
      },
      fileDownload() {
        printCode({
          itemId: this.codeId,
          itemType: 3,
          codeType: 1,
        }).then((res) => {
          // console.log(res);
          this.$message.success("已添加到打印队列");
        });
      },
      fileDownloadQR() {
        printCode({
          itemId: this.codeId,
          itemType: 3,
          codeType: 2,
        }).then((res) => {
          // console.log(res);
          this.$message.success("已添加到打印队列");
        });
      },
      enlargeBarcode(row) {
        var arr =
          this.baseUrl +
          "/api/barCode/showBarCode?id=" +
          row.id +
          "&type=" +
          row.type;
        this.srcList = arr.split(";");
      },
      enlargeQRCode(row) {
        var arr =
          this.baseUrl +
          "/api/barCode/showQRCode?id=" +
          row.id +
          "&type=" +
          row.type;
        this.srcList = arr.split(";");
      },
      // 钩子：在获取表格数据之前执行，false 则代表不获取数据
      [CRUD.HOOK.beforeRefresh]() {
        // this.$store.dispatch("hjuser/getStoreHouse");
        return true;
      },
      [CRUD.HOOK.afterRefresh]() {
        this.crud.data = this.crud.data.map(
          (item) => (item = {
            ...item,
            unit: Number(item.unit)
          })
        );
        return true;
      },
      [CRUD.HOOK.afterDelete]() {
        // this.$store.dispatch("hjuser/getStoreHouse");
      },
      [CRUD.HOOK.beforeSubmit](val) {
        this.openDoorId = val.form.cabinetId;
      },
      async [CRUD.HOOK.afterSubmit](val) {
        this.isApply = 1;
        this.isAudit = 0;
        this.getName()
      },
      //新建成功
      // async [CRUD.HOOK.afterSubmit](val) {
      //   try {
      //     const res = await openDoor({id:this.openDoorId})
      //     this.crud.notify(res, CRUD.NOTIFICATION_TYPE.SUCCESS)
      //      setTimeout(async ()=>{
      //         await closeDoor({id:this.openDoorId})
      //      },20000)
      //   } catch (error) {
      //     this.crud.notify('开门失败', CRUD.NOTIFICATION_TYPE.ERROR)
      //   }
      // },
    },
  };
</script>

<style scoped lang="scss">
  .el-form::v-deep {
    div.unit {
      .el-form-item__content {
        margin-left: 30px !important;
      }
    }
  }

  .el-table ::v-deep .cell {
    display: flex;
    align-items: center;
    justify-content: center;

    .isForbiddenBtn {
      width: 43px;
      height: 28px;
      line-height: 28px;
      text-align: center;
      margin-right: 5px;
      padding: 0;
    }

    .barCode {
      display: flex;
      flex-direction: column;
      align-items: center;
    }
  }

  .head-container {
    width: 100%
  }
</style>
